package com.ffapp.demo.notice;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ffapp.demo.R;
import com.ffapp.demo.basis.BasisActivity;
import com.ffapp.demo.basis.Constants;
import com.ffapp.demo.bean.BaseListData;
import com.ffapp.demo.bean.BaseListDataListBean;
import com.ffapp.demo.bean.ContactBizData;
import com.ffapp.demo.bean.ContactListBean;
import com.ffapp.demo.bean.ContactListData;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.IntentUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

/**
 * 通讯录
 */
public class ReceiverChooseActivity extends BasisActivity {


    @BindView(R.id.recyclerview)
    XRecyclerView mRecyclerView;
    @BindView(R.id.text_dept_name)
    TextView text_dept_name;
    @BindView(R.id.img_checkbox_all)
    ImageView img_checkbox_all;

    private MyAdapterList mAdapter;
    private ContactListBean mListBean;
    private ContactListBean mListBeanOrg;
    private ContactListBean mListBeanChecked;

    private BaseListDataListBean mParamsDeptList;
    private BaseListData mParamsDept;


    @BindView(R.id.edit_search)
    EditText edit_search;
    String searchkey = "";

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.notice_receiver_choose_activity);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setVerticalScrollBarEnabled(true);
        mRecyclerView.setLayoutManager(layoutManager);
//        mRecyclerView.setEmptyView(findViewById(R.id.refresh_view));
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mListBean.refresh();
                getList();
            }

            @Override
            public void onLoadMore() {
                getList();
            }
        });
        mRecyclerView.setPullRefreshEnabled(false);
        mRecyclerView.setLoadingMoreEnabled(false);
        setTitle("请选择推送对象");
        setTitleLeftButton(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                onBackPressed();
                finish();
            }
        });

        edit_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView view, int action,
                                          KeyEvent event) {
                // TODO Auto-generated method stub
                if (action == EditorInfo.IME_ACTION_DONE || action == EditorInfo.IME_ACTION_SEARCH) {
                   search();
                }
                return true;
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mListBeanChecked = new ContactListBean();

        String[] ids = getIntent().getStringArrayExtra("data");
        if(ids != null && ids.length > 0){
            ContactListData contactListData;
           for(String id:ids){
               contactListData = new ContactListData();
               contactListData.setId(id);
               mListBeanChecked.getList().add(contactListData);
           }
        }

        mListBean = new ContactListBean();
        setListView();

        getList();
//        getListFromCache();
//        getFromCache();
        findViewById(R.id.view_search_zone).setVisibility(View.GONE);
        setTitleRightText("确认", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onOkClick();
            }
        });
    }

    void onOkClick(){

        Intent intent = new Intent();
        intent.putExtra("data",mListBeanChecked.getParamsString());
        setResult(Activity.RESULT_OK,intent);
        finish();
    }

    private void setListView() {
        if (mAdapter == null) {
            mAdapter = new MyAdapterList();
            mRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }

    private void onListViewComplete() {
        mRecyclerView.refreshComplete();
        mRecyclerView.loadMoreComplete();
//        mRecyclerView.setLoadingMoreEnabled(mListBean.hasNextPage());
        mRecyclerView.setLoadingMoreEnabled(false);
        setEmptyView();
    }

    private void setEmptyView() {
        findViewById(R.id.refresh_view).setVisibility(View.GONE);
//        if (mListBean == null || mListBean.getList().size() == 0) {
//            findViewById(R.id.refresh_view).setVisibility(View.VISIBLE);
////            ((ImageView)findViewById(R.id.refresh_img)).setImageResource(R.drawable.lack_caveat);
////            findViewById(R.id.refresh_text_empty).setVisibility(View.VISIBLE);
////            ((TextView)findViewById(R.id.refresh_text_empty)).setText("暂无任何告警信息");
//            findViewById(R.id.refresh_view).setOnClickListener(
//                    new View.OnClickListener() {
//                        public void onClick(View v) {
//                            mRecyclerView.refresh();
//                        }
//                    });
//        } else {
//            findViewById(R.id.refresh_view).setVisibility(View.INVISIBLE);
//        }
    }

    private void getListFromCache(){
        mListBeanOrg = ContactListBean.getFromCache();
        if(mListBeanOrg == null){
            getList();
            return;
        }
        mParamsDeptList = mListBeanOrg.getDeptSearchList();
        mParamsDept = mParamsDeptList.getList().get(0);
        onDeptChoosed();
    }
    private void getList() {
        MyParams params = new MyParams();
        showProgress();
//        params.put("showAll", "false");
        MyHttpUtils.post(Constants.URL_NOTICE_GET_NOTICETREE, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        mListBeanOrg = (ContactListBean) result;
                        mListBeanOrg.save();
                        mParamsDeptList = mListBeanOrg.getDeptSearchList();
                        mParamsDept = mParamsDeptList.getList().get(0);
                        onDeptChoosed();
//                        mListBean = mListBeanOrg;
//                        mListBean.processList();
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);
//            mListBean = new ServiceNewListBean();
                        setListView();
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        hideLoading();
                        onListViewComplete();
                    }
                },
                0, ContactListBean.class);

    }

    @SuppressLint("StaticFieldLeak")
    void getListLocal(){
        if(mListBeanOrg == null)return;
        showLoading();
        new AsyncTask<String, Integer, String>() {
            @Override
            protected String doInBackground(String... strings) {
                if(mParamsDept != null && !TextUtils.isEmpty(searchkey)){
                    mListBean = mListBeanOrg.getByDept(mParamsDept);
                    mListBean = mListBean.getBySearchKey(searchkey);
                }else if(!TextUtils.isEmpty(searchkey)){
                    mListBean = mListBeanOrg.getBySearchKey(searchkey);
                }else  if(mParamsDept != null){
                    mListBean = mListBeanOrg.getByDept(mParamsDept);
                }else {
                    mListBean = mListBeanOrg.getBySearchKey("");
                }
                mListBean.processList();
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                mAdapter.notifyDataSetChanged();
                hideLoading();
            }

        }.execute("");


    }

    @OnClick(R.id.img_search)
    void search() {
        searchkey = edit_search.getText().toString().trim();
//        if (TextUtils.isEmpty(searchkey)) {
//            showToast(R.string.app_please_input_search_key);
//            return;
//        }
        getListLocal();
    }
    @OnClick(R.id.img_cancel)
    void searchCancel() {
        edit_search.setText("");
    }

    @OnClick(R.id.view_search_dept)
    void onSearchDetpClick(){
        if(mParamsDeptList == null)return;

        final String[] items = mParamsDeptList.getListStringGroup();
        new QMUIDialog.CheckableDialogBuilder(mContext)
                .setTitle(  "请选择部门")
                .setCheckedIndex(mParamsDeptList.getCheckedPosition(mParamsDept))
                .addItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mParamsDept = mParamsDeptList.getList().get(which);
                        onDeptChoosed();
                        dialog.dismiss();
                    }
                })
                .create().show();
    }

    void onDeptChoosed(){
        if(mParamsDept == null){
            return;
        }
        text_dept_name.setText(mParamsDept.getName());
        getListLocal();
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        if(mParamsDeptList != null && mParamsDept != null && (!mParamsDept.getName().equals("全部") || !TextUtils.isEmpty(searchkey))){
            mParamsDept = mParamsDeptList.getList().get(0);
            text_dept_name.setText(mParamsDept.getName());
            edit_search.setText("");
            search();
        }else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            mRecyclerView.refresh();
        }
    }

    public class MyAdapterList extends RecyclerView.Adapter<MyAdapterList.ViewHolder> {

        public MyAdapterList() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.notice_receiverchoose_contact_list_item, viewGroup, false);
            return new ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return mListBean == null ? 0 : mListBean.getListResultCount();
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.list_item)
            public View list_item;
            @BindView(R.id.view_dept_zone)
            public View view_dept_zone;
            @BindView(R.id.img_arrow)
            public ImageView img_arrow;
            @BindView(R.id.img_checkbox)
            public ImageView img_checkbox;
            @BindView(R.id.text_dept_name)
            public TextView text_dept_name;
            @BindView(R.id.view_contact_zone)
            public View view_contact_zone;
            @BindView(R.id.text_name)
            public TextView text_name;
            @BindView(R.id.text_job)
            public TextView text_job;
            @BindView(R.id.text_phone)
            public TextView text_phone;
            @BindView(R.id.img_call)
            public ImageView img_call;
            @BindView(R.id.text_divider)
            public TextView text_divider;
            @BindView(R.id.img_checkbox_contact)
            public ImageView img_checkbox_contact;


            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);

            }

            public void bind(int position) {
                ContactListData data = mListBean.getItemByListPosition(position);
                if(data.isLeaf_BOOLEAN()){
                    img_checkbox_contact.setImageResource(mListBeanChecked.isDateChecked(data)?R.drawable.checkbox_blue_icon_selected :R.drawable.checkbox_blue_icon_unselected);
                    view_contact_zone.setVisibility(View.VISIBLE);
                    view_dept_zone.setVisibility(View.GONE);

                    text_name.setText(data.getTitle());
//                    ContactBizData bizData = data.getBizData();
//                    if(bizData != null){
////                        text_dept_name.setText(bizData.getDeptName());
////                        text_job.setText(bizData.getDeptName());
////                        text_job.setText(bizData.getPost());
//                        text_name.setText(bizData.getName());
//                        text_phone.setText(bizData.getPhone());
////                        if(TextUtils.isEmpty(bizData.getPost())){
////                            text_divider.setVisibility(View.INVISIBLE);
////                        }else {
////                            text_divider.setVisibility(View.VISIBLE);
////                        }
//                    }
                    int level = data.getLevel();
                    view_contact_zone.setPadding(35*level,0,0,0);
                }else {
                    if(ContactListBean.isGroupDateNoMember(data)){
                        img_checkbox.setImageResource(R.drawable.checkbox_blue_icon_unselected);
                    }else {
                        if(mListBeanChecked.isDateGroupAllChecked(data)){
                            img_checkbox.setImageResource(R.drawable.checkbox_blue_icon_selected );
                        }else {
                            if(mListBeanChecked.isDateGroupHasChecked(data)){//半勾选
                                img_checkbox.setImageResource(R.drawable.checkbox_blue_icon_halfseleted);
                            }else {
                                img_checkbox.setImageResource(R.drawable.checkbox_blue_icon_unselected);
                            }

                        }
                    }

                    view_contact_zone.setVisibility(View.GONE);
                    view_dept_zone.setVisibility(View.VISIBLE);
                    text_dept_name.setText(data.getTitle());
                    img_arrow.setImageResource(data.isExpand()?R.drawable.notice_icon_arrow_down:R.drawable.icon_into);

                    int level = data.getLevel();
                    view_dept_zone.setPadding(35*level,0,0,0);
                }
                view_dept_zone.setTag(position);
                img_call.setTag(position);
                img_checkbox.setTag(position);
                img_checkbox_contact.setTag(position);

            }

            @OnClick(R.id.view_dept_zone)
            void onDeptZoneClick(View view){
                int position = (int) view.getTag();
                mListBean.expandOrCloseByListPosition(position);
                notifyDataSetChanged();
            }
            @OnClick(R.id.img_checkbox)
            void onDeptCheckboxClick(View view){
                int position = (int) view.getTag();
                ContactListData groupData = mListBean.getItemByListPosition(position);
                if(mListBeanChecked.isDateGroupAllChecked(groupData)){
                    mListBeanChecked.setGroupAllRemove(groupData);
                }else {
                    mListBeanChecked.setGroupAllCheck(groupData);
                }
                notifyDataSetChanged();
            }
            @OnClick(R.id.img_checkbox_contact)
            void onContactCheckboxClick(View view){
                int position = (int) view.getTag();
                ContactListData contactListData = mListBean.getItemByListPosition(position);
                mListBeanChecked.addOrRemoveData(contactListData);
                notifyDataSetChanged();
            }
            @OnClick(R.id.img_call)
            void onImgCallClick(View view){
                int position = (int) view.getTag();
              ContactListData listData = mListBean.getItemByListPosition(position);
              if(listData.getBizData() == null)return;
              ContactBizData bizData = listData.getBizData();
                if(TextUtils.isEmpty(bizData.getPhone())){
                  showToast("该联系人没有号码");
                  return;
              }
                IntentUtils.callToDial(mContext,bizData.getPhone());
            }
        }
    }


    @OnClick(R.id.img_checkbox_all)
    void onAllCheckClick(){
        if(mListBeanChecked.isAllCheck(mListBean)){
            mListBeanChecked.getList().clear();
            mAdapter.notifyDataSetChanged();
        }else {
            mListBeanChecked.setAllCheck(mListBean);
            mAdapter.notifyDataSetChanged();
        }
        setAllCheckView();
    }

    void setAllCheckView(){
        if(mListBeanChecked.isAllCheck(mListBean)){
            img_checkbox_all.setImageResource(R.drawable.checkbox_blue_icon_selected);
        }else {
            img_checkbox_all.setImageResource(R.drawable.checkbox_blue_icon_unselected);
        }
    }
}
